package jp.co.cos.ittrick.channel.controller.client;

import java.util.ArrayList;
import java.util.List;

import jp.co.cos.ittrick.channel.meta.PageModelMeta;
import jp.co.cos.ittrick.channel.model.ChapterModel;
import jp.co.cos.ittrick.channel.model.PageModel;
import jp.co.cos.ittrick.channel.service.ChapterService;
import jp.co.cos.ittrick.channel.service.PageService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.Key;

public class InsertPageController extends Controller {

    private PageService pageService;
    private ChapterService chapterService;

    public InsertPageController() {
        pageService = new PageService();
        chapterService = new ChapterService();
    }

    @Override
    public Navigation run() throws Exception {

        // リクエストパラメータ
        String chapter = asString("chapter");
        String name = asString("name");
        Integer index = this.asInteger("index");

        List<String> keyWordList = new ArrayList<String>();

        // 親の取得
        ChapterModel chapterModel = chapterService.getChapterByKey(Integer.valueOf(chapter));

        // Modelの設定
        PageModel model = new PageModel();
        model.setName(name);
        model.setIndex(index);
        model.setKeyWordList(keyWordList);
        model.getChapterModelRef().setModel(chapterModel);

        // Insert
        Key key = pageService.insert(model);

        model = pageService.getPageByKey((int)key.getId());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        response.getWriter().println(PageModelMeta.get().modelToJson(model));
        response.flushBuffer();

        return null;
    }
}
